﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    public partial class ComicDownloadChapterPage : PhoneApplicationPage
    {
        private IEnumerable<BackgroundTransferRequest> transferRequests;
        private DownloadComic downloadComic = null;

        public ComicDownloadChapterPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (base.NavigationContext.QueryString.ContainsKey("jsonDownloadComic"))
            {
                string jsonDownloadComic = string.Empty;
                base.NavigationContext.QueryString.TryGetValue("jsonDownloadComic", out jsonDownloadComic);
                if (string.IsNullOrWhiteSpace(jsonDownloadComic))
                {
                    base.NavigationService.GoBack();
                    return;
                }
                downloadComic = JSONHelper.Deserialize<DownloadComic>(jsonDownloadComic);
                if (downloadComic == null)
                {
                    base.NavigationService.GoBack();
                    return;
                }
            }
            // When the page loads, refresh the list of file transfers.
            InitialTransferStatusCheck();
            UpdateUI();
        }

        private void UpdateUI()
        {
            // Update the list of transfer requests
            UpdateRequestsList();

            //// Update the TransferListBox with the list of transfer requests.
            //TransferListBox.ItemsSource = transferRequests;

            //// If there are 1 or more transfers, hide the "no transfers"
            //// TextBlock. IF there are zero transfers, show the TextBlock.
            //if (TransferListBox.Items.Count > 0)
            //{
            //    EmptyTextBlock.Visibility = Visibility.Collapsed;
            //}
            //else
            //{
            //    EmptyTextBlock.Visibility = Visibility.Visible;
            //}

        }

        private void InitialTransferStatusCheck()
        {
            UpdateRequestsList();

            foreach (var transfer in transferRequests)
            {
                transfer.TransferStatusChanged += transfer_TransferStatusChanged;
                transfer.TransferProgressChanged += transfer_TransferProgressChanged;
                ProcessTransfer(transfer);
            }
        }



        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            UpdateUI();
        }

        void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            ProcessTransfer(e.Request);
            UpdateUI();
        }

        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
                case TransferStatus.Completed:

                    // If the status code of a completed transfer is 200 or 206, the
                    // transfer was successful
                    if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                    {
                        // Remove the transfer request in order to make room in the 
                        // queue for more transfers. Transfers are not automatically
                        // removed by the system.
                        RemoveTransferRequest(transfer.RequestId);

                        // In this example, the downloaded file is moved into the root
                        // Isolated Storage directory
                        using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            string filename = transfer.Tag;
                            //if (isoStore.FileExists(filename))
                            //{
                            //    isoStore.DeleteFile(filename);
                            //}
                            //isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
                        }
                    }
                    else
                    {
                        // This is where you can handle whatever error is indicated by the
                        // StatusCode and then remove the transfer from the queue. 
                        RemoveTransferRequest(transfer.RequestId);

                        if (transfer.TransferError != null)
                        {
                            // Handle TransferError if one exists.
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // Try to remove the transfer from the background transfer service.
            try
            {
                BackgroundTransferService.Remove(transferToRemove);
            }
            catch (Exception e)
            {
                // Handle the exception.
            }
        }


        /// <summary>
        /// 该方法使用 BackgroundTransferService 类的 Requests 属性检索当前已为该应用注册的传输请求列表。
        /// <para>该属性返回新 BackgroundTransferRequest 对象的列表。</para>
        /// <para>由于对象是新的，因此请确保针对任何现有对象引用调用 Dispose 以避免内存泄露。</para>
        /// </summary>
        private void UpdateRequestsList()
        {
            // The Requests property returns new references, so make sure that
            // you dispose of the old references to avoid memory leaks.
            if (transferRequests != null)
            {
                foreach (var request in transferRequests)
                {
                    request.Dispose();
                }
            }
            transferRequests = BackgroundTransferService.Requests;
        }
    }
}